//
//  HWGameCommunityController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/10/18.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
import JXPagingView
class HWGameCommunityController: HWBaseViewController {
    @objc var communityId = ""
    var topBgImageView:UIImageView!
    var backButton:UIButton!
//    var allButton:UIButton!
    
    var topView:HWGameCommunityTopView!
    var pagingView:JXPagingView!
    var segmentBgView:UIView!
    var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect.zero)
    var segmentedDataSource: JXSegmentedTitleDataSource!
    
    var httpManager = HWGameCommunityHttpManager()
    var titles:[String] = Array()
    var tagModels:[HWGameCommunityFenLeiModel] = []
    
    var selectIndex = 0 {
        didSet{
            DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {                
                self.segmentedView.selectItemAt(index: self.selectIndex)
            }
            
        }
    }
    
    private let pushButton = c_make_ex(UIImageView.self)
        .image("Push").end()
//    var releaseView:UIView!
//    var releaseButton:UIButton!
//    var messageButton:UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        loadData()
        
        addAction()
    }
}

extension HWGameCommunityController {
    private func initUI() -> Void {
        
        navigationView.isHidden = true
        view.backgroundColor = "#E8E9EB".toColor
        
        topBgImageView = UIImageView()
        view.addSubview(topBgImageView)
        
        backButton = UIButton(type: .custom)
        backButton.setImage(UIImage(named: "new_back"), for: .normal)
        backButton.addTarget(self, action: #selector(backButtonClick(_:)), for: .touchUpInside)
        view.addSubview(backButton)
        
//        allButton = UIButton(type: .custom)
//        allButton.frame = CGRect(x: 0, y: 0, width: 82*widthScale, height: 28*widthScale)
//        allButton.setTitle("全部社区", for: .normal)
//        allButton.titleLabel?.font = .boldSystemFont(ofSize: 13*widthScale)
//        allButton.setTitleColor(.colorWithHexString(hexString: "#333333"), for: .normal)
//        allButton.backgroundColor = .colorWithAlphaHexString(hexString: "#FFFFFF", alpha: 0.72)
//        allButton.addTarget(self, action: #selector(allButtonClick(_:)), for: .touchUpInside)
//        view.addSubview(allButton)
//        allButton.addCorner(conrners: [.topLeft,.bottomLeft], radius: 14*widthScale)
        
        topView = HWGameCommunityTopView()
        topView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 258*widthScale)
        
        segmentBgView = UIView()
        segmentBgView.backgroundColor = "#E8E9EB".toColor
        
        segmentedDataSource = JXSegmentedTitleDataSource()
        segmentedDataSource.titles = []
        segmentedDataSource.isTitleColorGradientEnabled = true
        segmentedDataSource.titleNormalColor = UIColor.colorWithHexString(hexString: "#47494D")
        segmentedDataSource.titleSelectedColor = UIColor.colorWithHexString(hexString: "#2E3033")
        segmentedDataSource.titleNormalFont = 12.font_semiBold!
        segmentedDataSource.titleSelectedFont = 12.font_semiBold!
        segmentedDataSource.isItemSpacingAverageEnabled = false
        
        segmentedView.dataSource = segmentedDataSource
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorHeight = 3*widthScale
        indicator.indicatorCornerRadius = 0
        indicator.verticalOffset = 3
        indicator.indicatorColor = .black
        
        segmentedView.indicators = [indicator]
        segmentedView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 35*widthScale)
        segmentedView.backgroundColor = "#E8E9EB".toColor
//        segmentedView.delegate = self
        segmentBgView.addSubview(self.segmentedView)
        
        pagingView = JXPagingView(delegate: self)
        pagingView.automaticallyDisplayListVerticalScrollIndicator = false
        pagingView.mainTableView.backgroundColor = .clear
        pagingView.listContainerView.isCategoryNestPagingEnabled = true
        view.addSubview(pagingView)
        segmentedView.listContainer = pagingView.listContainerView
        
        let tapG = UITapGestureRecognizer(target: self, action: #selector(releaseButtonClick))
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        
        pushButton.isUserInteractionEnabled = true
        pushButton.addGestureRecognizer(tapG)
        pushButton.addGestureRecognizer(panGesture)
        
        view.addSubview(pushButton)
//        releaseView = UIView()
//        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
//        releaseView.addGestureRecognizer(panGesture)
//        view.addSubview(releaseView)
//        
//        releaseButton = UIButton(type: .custom)
//        releaseButton.setBackgroundImage(UIImage(named: "communityRelease"), for: .normal)
//        releaseButton.addTarget(self, action: #selector(releaseButtonClick(_:)), for: .touchUpInside)
//        releaseView.addSubview(releaseButton)
//        
//        messageButton = UIButton(type: .custom)
//        messageButton.setBackgroundImage(UIImage(named: "communityMessage"), for: .normal)
//        messageButton.addTarget(self, action: #selector(messageButtonClick(_:)), for: .touchUpInside)
//        releaseView.addSubview(messageButton)
        
    }
    
    private func initFrame() -> Void {
        topBgImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(210*widthScale)
        }
        
        backButton.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(56*widthScale)
            make.height.equalTo(44*widthScale)
            make.top.equalTo(CGFloat.statusHeight)
        }
        
//        allButton.snp.makeConstraints { make in
//            make.right.equalToSuperview()
//            make.width.equalTo(82*widthScale)
//            make.height.equalTo(28*widthScale)
//            make.centerY.equalTo(backButton)
//        }
        
        pagingView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(92*widthScale)
            make.bottom.equalToSuperview()
        }
        
        segmentedView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(35*widthScale)
        }
        
//        releaseView.snp.makeConstraints { make in
//            make.right.equalTo(-18*widthScale)
//            make.width.equalTo(49*widthScale)
//            make.height.equalTo(93*widthScale)
//            make.bottom.equalTo(-80*widthScale)
//        }
//        
//        releaseButton.snp.makeConstraints { make in
//            make.left.right.top.equalToSuperview()
//            make.height.equalTo(50*widthScale)
//        }
//        
//        messageButton.snp.makeConstraints { make in
//            make.left.right.bottom.equalToSuperview()
//            make.height.equalTo(43*widthScale)
//        }
        pushButton.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(88*widthScale)
            make.height.equalTo(88*widthScale)
            make.bottom.equalTo(-CGFloat.tabBar_height)
        }
    }
}
//extension JXPagingListContainerView: JXSegmentedViewListContainer {}
extension HWGameCommunityController {
    @objc func backButtonClick(_ button:UIButton) -> Void {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.pushButton.center = CGPoint(x: self.pushButton.center.x + point.x, y: self.pushButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.pushButton.center.x +  point.x, y: self.pushButton.center.y + point.y)
            if newPoint.x < screenWidth / 2.0 {
                newPoint.x = self.pushButton.bounds.width/2 + 17*widthScale
            } else {
                newPoint.x = screenWidth - self.pushButton.bounds.width/2 - 17*widthScale
            }
            if newPoint.y <= self.pushButton.bounds.height/2 + 18*widthScale + navigationView.bounds.height{
                newPoint.y = self.pushButton.bounds.height/2 + 18*widthScale + navigationView.bounds.height
            } else if newPoint.y >= self.view.bounds.height - self.pushButton.bounds.height/2 - 18*widthScale {
                newPoint.y = self.view.bounds.height - self.pushButton.bounds.height/2 - 18*widthScale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.pushButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
    
    @objc func releaseButtonClick() {
        let release = HWGameCommunityReleaseController()
        release.communityId = self.communityId
        release.type = self.segmentedView.selectedIndex
        self.navigationController?.pushViewController(release, animated: true)
    }
    
    @objc func messageButtonClick(_:UIButton) -> Void {
        let message = HWGameCommentInteractController()
        self.navigationController?.pushViewController(message, animated: true)
    }
}


extension HWGameCommunityController:JXPagingViewDelegate {
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        
        if tagModels[index].type == "3" {
            let strategyVC = HWStrategyViewController()
            strategyVC.shequID = self.communityId
            return strategyVC
        }else{
            let list = HWGameCommunityListController()
            list.type = tagModels[index].type
            list.communityId = self.communityId
            return list
        }        
    }
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        if (self.topView.model?.news.count ?? 0) > 0 {
            let height = 143*widthScale + CGFloat((self.topView.model?.news.count ?? 0)*30)*widthScale + 24*widthScale
            return Int(height)
        }
        return Int(143*widthScale)
//        return Int(236*widthScale)
        
    }
    
    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return topView
    }
    
    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return Int(46*widthScale)
    }
    
    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentBgView
    }
    
    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return segmentedDataSource.dataSource.count
    }
    
}
extension HWGameCommunityController:JXSegmentedViewDelegate,JXPagingMainTableViewGestureDelegate {
    
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
  
    }
    
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}

extension HWGameCommunityController {
    func loadData() -> Void {
        httpManager.getGameCommunityTop(communityId: self.communityId) { model in
            self.topBgImageView.kf.setImage(with: URL(string: model.bgimg))
            self.topView.model = model
            self.titles.removeAll()
            self.tagModels.removeAll()
            for mod in model.fenlei {
                self.titles.append(mod.name)
                self.tagModels.append(mod)
            }
            self.pagingView.reloadData()
            
            self.segmentedDataSource.titles = self.titles
            self.segmentedView.reloadData()
            
        } failure: { errorString in
            self.view.showHUD(title: errorString)
        }

    }
}


extension HWGameCommunityController {
    func addAction() -> Void {
        self.topView.followButtonClick = {
            mod in
            self.httpManager.gameCommunityFollow(id: self.communityId) { message in
                self.loadData()
            } failure: { errorString in
                self.view.showHUD(title: errorString)
            }

        }
        
        self.topView.didClickNews = {
            mod in
//            let webView = HWWebViewGameViewController()
//            webView.urlString = HWGlobalConst.baseUrl + "?ct=aznews&ac=info&id=" + mod.id + "&language=" + HWjianzhiduiObject.returnLanguageAcquisition()
//            webView.gname = mod.title
//            webView.isPush = true
//            self.navigationController?.pushViewController(webView, animated: true)
            let detail = HWGameCommunityDetailController()
            detail.newsId = mod.id
            self.navigationController?.pushViewController(detail, animated: true)
        }
    }
    
    @objc func allButtonClick(_:UIButton) -> Void {
        let sheet = HWGameCommunityAllListSheet()
        sheet.show()
    }
}
